import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth.store'

const routes = [
    {
        path: '/',
        name: 'home',
        component: () => import('@/pages/Dashboard.vue')
    },
    {
        path: '/auth',
        name: 'auth',
        component: () => import('@/pages/AuthPage.vue')
    },
    {
        path: '/create',
        name: 'create',
        component: () => import('@/pages/EditorPage.vue'),
        meta: { requiresCreator: true }
    },
    {
        path: '/edit/:id',
        name: 'edit',
        component: () => import('@/pages/EditorPage.vue'),
        meta: { requiresCreator: true }
    },
    {
        path: '/survey/:id',
        name: 'survey',
        component: () => import('@/pages/RespondPage.vue')
    },
    {
        path: '/results/:id',
        name: 'results',
        component: () => import('@/pages/ResultsPage.vue'),
        meta: { requiresCreator: true }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const authStore = useAuthStore()

    // 初始化认证状态
    if (!authStore.isAuthenticated) {
        authStore.initialize()
    }

    // 检查需要创建者权限的路由
    if (to.meta.requiresCreator) {
        if (authStore.isAuthenticated && authStore.currentUser?.role === 'creator') {
            next()
        } else {
            next({ name: 'auth' })
        }
    } else {
        next()
    }
})

export default router
